﻿using QQTools.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QQTools.Utils
{
    public class Win32Api
    {
        // SetWindowPos
        [DllImport("user32.dll")]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
        // SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE
        public static uint SWP_NOSIZE = 0x0001;
        public static uint SWP_NOMOVE = 0x0002;
        public static uint SWP_NOZORDER = 0x0004;
        public static uint SWP_NOACTIVATE = 0x0010;
        public static uint SWP_SHOWWINDOW = 0x0040;
        public static uint SWP_HIDEWINDOW = 0x0080;
        public static uint SWP_FRAMECHANGED = 0x0020;
        public static uint SWP_NOSENDCHANGING = 0x0400;
        public static uint SWP_NOCOPYBITS = 0x0100;
        // 定义 SendMessage 命令常亮
        public const uint LVM_SCROLL = 0x1014;  // 窗口滚动
        public const uint WM_CLOSE = 0x0010;    // 关闭窗口
        public const uint WM_SETTEXT = 0x000C;         // 设置窗口文本
        // 定义 ShowWindow 命令常量
        public const int SW_RESTORE = 9; // 还原窗口
        public const int SW_HIDE = 0;    // 隐藏窗口
        public const int SW_SHOW = 5;   // 显示窗口

        // 定义 ShowWindow 方法
        [DllImport("user32.dll")]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        /// <summary>
        /// 获取窗口句柄
        /// </summary>
        /// <param name="lpClassName"></param>
        /// <param name="lpWindowName"></param>
        /// <returns></returns>

        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        /// <summary>
        /// 获取窗口文本，文本会塞入StringBuilder中，需要指明字符串最大长度nMaxCount
        /// </summary>
        /// <param name="hwnd">窗口句柄</param>
        /// <param name="lpString">返回目标窗口的内容</param>
        /// <param name="nMaxCount">允许返回的字符数量上限</param>
        /// <returns>实际获取到的文本长度</returns>
        [DllImport("User32.dll", EntryPoint = "GetWindowText")]
        public static extern int GetWindowText(IntPtr hwnd, StringBuilder lpString, int nMaxCount);

        // 判断窗口是否可见
        /// <summary>
        /// 判断目标窗口是否可见
        /// </summary>
        /// <param name="hWnd">窗口句柄</param>
        /// <returns>可见true,不可见false</returns>
        [DllImport("user32.dll")]
        public static extern bool IsWindowVisible(IntPtr hWnd);

        /// <summary>
        /// 遍历所有窗口
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="lParam"></param>
        /// <returns></returns>
        public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
        [DllImport("user32.dll")]
        public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);

        /// <summary>
        /// 获取窗口文本长度
        /// </summary>
        /// <param name="hWnd"></param>
        /// <returns></returns>
        [DllImport("user32.dll", SetLastError = true)]
        private static extern int GetWindowTextLength(IntPtr hWnd);

        /// <summary>
        /// 获取窗口类名
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="lpClassName"></param>
        /// <param name="nMaxCount"></param>
        /// <returns></returns>
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);



        /// <summary>
        /// 获取指定窗口的线程和进程标识符。
        /// </summary>
        /// <param name="hwnd">窗口句柄。</param>
        /// <param name="PID">输出参数，用于接收窗口所属进程的标识符。</param>
        /// <returns>返回窗口所属线程的标识符。如果窗口句柄无效，返回 0。</returns>
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int PID);

        /// <summary>
        /// 获取指定窗口（或控件）在屏幕中的位置信息 （左边界，上边界，右边界，下边界）
        /// </summary>
        /// <param name="hWnd">窗口句柄</param>
        /// <param name="lpRect">LPRECT矩形结构的长指针,数据存储使用struct类型</param>
        /// <returns>获取成功返回非0值,失败返回0</returns>
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);


        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, string lParam);


        [DllImport("User32.dll", SetLastError = true)]
        public static extern bool IsWindow(IntPtr hWnd);

        /// <summary>
        /// 矩形范围信息（结构体）
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            /// <summary>
            /// 当前矩形范围的最左边界
            /// </summary>
            public int Left;
            /// <summary>
            /// 当前矩形的最上边界
            /// </summary>
            public int Top;
            /// <summary>
            /// 当前矩形的最右边界
            /// </summary>
            public int Right;
            /// <summary>
            /// 当前矩形的最下边界
            /// </summary>
            public int Bottom;
        }

        /// <summary>
        /// 根据窗口类名和窗口标题查找所有满足条件的窗口
        /// </summary>
        /// <param name="targetClassName">窗口类名</param>
        /// <param name="targetTitle">窗口标题</param>
        /// <returns>窗口句柄数组</returns>
        //public static List<IntPtr> FindAllWindows(string targetClassName, string targetTitle)
        //{
        //    List<IntPtr> matchedHandles = new List<IntPtr>();
        //    EnumWindowsProc callback = (hWnd, lParam) =>
        //    {
        //        const int maxLength = 256;
        //        StringBuilder classNameBuilder = new StringBuilder(maxLength);
        //        GetClassName(hWnd, classNameBuilder, maxLength);
        //        StringBuilder windowTitle = new StringBuilder(256);
        //        GetWindowText(hWnd, windowTitle, windowTitle.Capacity);

        //        if (classNameBuilder.ToString() == targetClassName && windowTitle.ToString() == targetTitle)
        //        {
        //            matchedHandles.Add(hWnd);
        //        }
        //        return true; // 继续遍历所有窗口
        //    };
        //    EnumWindows(callback, IntPtr.Zero);
        //    return matchedHandles;
        //}



        // Windows 消息常量
        private const int WM_LBUTTONDOWN = 0x0201;
        private const int WM_LBUTTONUP = 0x0202;

        // 将 x, y 坐标编码成 lParam
        private static IntPtr MakeLParam(int x, int y)
        {
            return (IntPtr)((y << 16) | (x & 0xFFFF));
        }

        /// <summary>
        /// 模拟鼠标点击
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public static void SendClick(IntPtr hWnd, int x, int y)
        {
            var lParam = MakeLParam(x, y);
            SendMessage(hWnd, WM_LBUTTONDOWN, (IntPtr)1, lParam);
            SendMessage(hWnd, WM_LBUTTONUP, IntPtr.Zero, lParam);
        }


        /// <summary>
        /// 根据窗口类名和窗口标题查找所有满足条件的窗口
        /// </summary>
        /// <param name="targetClassName">窗口类名</param>
        /// <param name="targetTitle">窗口标题</param>
        /// <param name="isVisible">true只寻找可见窗口 默认true</param>
        /// <returns>窗口句柄数组</returns>
        public static List<IntPtr> FindAllWindows(string targetClassName, string targetTitle, bool isVisible = true)
        {
            var matchedHandles = new List<IntPtr>();
            var classNameBuilder = new StringBuilder(256);
            var windowTitleBuilder = new StringBuilder(256);

            try
            {
                EnumWindows((hWnd, lParam) =>
                {
                    if (isVisible)
                    {
                        // 仅处理可见窗口 (可选)
                        if (!IsWindowVisible(hWnd))
                            return true;
                    }

                    classNameBuilder.Clear();
                    windowTitleBuilder.Clear();

                    if (GetClassName(hWnd, classNameBuilder, classNameBuilder.Capacity) > 0 &&
                        GetWindowText(hWnd, windowTitleBuilder, windowTitleBuilder.Capacity) > 0)
                    {
                        //if (classNameBuilder.ToString().Equals(targetClassName) &&
                        //    windowTitleBuilder.ToString().Equals(targetTitle))
                        //{
                        //    matchedHandles.Add(hWnd);
                        //}

                        if (classNameBuilder.ToString().Equals(targetClassName)) // 类名必须一致
                        {
                            if (string.IsNullOrEmpty(targetTitle) && string.IsNullOrEmpty(windowTitleBuilder.ToString())) // 目标标题为空且目标标题为空
                            {
                                matchedHandles.Add(hWnd);
                            }
                            else
                            {   // 目标标题不为空时 目标标题和窗口标题一致
                                if (windowTitleBuilder.ToString().Equals(targetTitle))
                                {
                                    matchedHandles.Add(hWnd);
                                }
                            }

                        }

                    }
                    return true; // 继续遍历所有窗口
                }, IntPtr.Zero);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[FindAllWindows] 查找异常->窗口标题:{targetTitle} 类名:{targetClassName}, 原因:{ex.Message}", ex);
            }

            return matchedHandles;
        }

        /// <summary>
        /// 获取窗口的 PID 和句柄
        /// </summary>
        /// <param name="windowClass"></param>
        /// <param name="windowTitle"></param>
        /// <param name="isVisible">true只寻找可见窗口 默认true, QQ主窗口如果最小化,这里使用false,不可见的窗口也要寻找,否则找不到</param>
        /// <returns></returns>
        public static Dictionary<int, IntPtr> GetPidAndHandle(string windowClass = "TXGuiFoundation", string windowTitle = "QQ", bool isVisible = false)
        {

            try
            {
                // 获取所有符合条件的窗口句柄
                List<IntPtr> hwndList = FindAllWindows(windowClass, windowTitle, isVisible);
                if (hwndList == null || hwndList.Count == 0)
                {
                    LogManager.Error("[GetPidAndHandle] 未找到任何符合条件的窗口句柄。");
                    return new Dictionary<int, IntPtr>();
                }

                var hwndPidDict = new Dictionary<int, IntPtr>();

                foreach (var hwnd in hwndList)
                {
                    try
                    {
                        // 获取窗口对应的进程 ID
                        if (Win32Api.GetWindowThreadProcessId(hwnd, out int pid) == 0)
                        {
                            LogManager.Error($"[GetPidAndHandle] 无法获取窗口句柄 {hwnd} 的进程 ID。");
                            continue;
                        }

                        if (pid == 0)
                        {
                            LogManager.Error($"[GetPidAndHandle] 窗口句柄 {hwnd} 对应的进程 ID 无效。");
                            continue;
                        }

                        // 检查字典中是否已存在该 PID
                        if (hwndPidDict.ContainsKey(pid))
                        {
                            LogManager.Error($"[GetPidAndHandle] PID {pid} 已存在于字典中，跳过当前窗口句柄 {hwnd}。");
                            continue;
                        }

                        // 添加到字典
                        hwndPidDict[pid] = hwnd;
                        LogManager.Info($"[GetPidAndHandle] 成功添加：PID:{pid} 窗口句柄:{hwnd}");
                    }
                    catch (Exception ex)
                    {
                        LogManager.Error($"[GetPidAndHandle] 处理窗口句柄 {hwnd} 时发生错误: {ex.Message}");
                    }
                }

                return hwndPidDict;

            }
            catch (Exception ex)
            {
                LogManager.Error($"[GetPidAndHandle] 获取 QQ PID 和句柄时发生错误: {ex.Message}");
                return new Dictionary<int, IntPtr>();
            }
        }


        /// <summary>
        /// 根据pid,name,classname获取窗口句柄
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="name"></param>
        /// <param name="className"></param>
        /// <param name="isVisible">true默认只寻找可见的窗口,false:可见+不可见窗口都寻找</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public static IntPtr GetWindowHandle(int pid, string name, string className, bool isVisible = true)
        {
            try
            {
                List<IntPtr> hwndList = FindAllWindows(className, name, isVisible);
                if (hwndList == null || hwndList.Count == 0)
                {
                    LogManager.Error("[GetWindowHandle] 未找到任何符合条件的窗口句柄。");
                    return IntPtr.Zero;
                }
                foreach (var hwnd in hwndList)
                {
                    try
                    {
                        if (GetWindowThreadProcessId(hwnd, out int _pid) == 0)
                        {
                            LogManager.Error($"[GetWindowHandle] 无法获取窗口句柄 {hwnd} 的进程 ID。");
                            continue;
                        }
                        if (_pid == pid)
                        {
                            LogManager.Info($"[GetWindowHandle] 成功获取到 PID:{pid} 窗口句柄:{hwnd}");
                            return hwnd;
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManager.Error($"[GetWindowHandle] 获取 PID 和窗口句柄时发生错误: {ex.Message}");
                        return IntPtr.Zero;
                    }
                }

            }
            catch (Exception ex)
            {
                LogManager.Error($"[GetWindowHandle] 获取 PID 和窗口句柄时发生错误: {ex.Message}");

            }
            return IntPtr.Zero;
        }



        /// <summary>
        /// 置顶窗口, 如果窗口最小化，则取消最小化,
        /// </summary>
        /// <param name="hWnd"></param>
        public static void SetTopWindow(IntPtr hWnd)
        {
            try
            {
                if (IsWindowVisible(hWnd))
                {
                    ShowWindow(hWnd, SW_RESTORE);
                    SetForegroundWindow(hWnd);
                }
                else
                {
                    ShowWindow(hWnd, SW_SHOW);
                    SetForegroundWindow(hWnd);
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[SetTopWindow] 置顶窗口时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 枚举所有窗口并筛选出标题以指定字符串结尾且属于特定进程的窗口。
        /// </summary>
        /// <param name="suffix">窗口标题需要匹配的后缀。</param>
        /// <param name="targetProcessId">目标进程的 ID。</param>
        /// <returns>符合条件的窗口信息列表。</returns>
        public static List<(IntPtr Handle, string Title)> FindWindowsByTitleSuffixAndProcessId(string suffix, int targetProcessId)
        {
            var result = new List<(IntPtr Handle, string Title)>();

            // 枚举所有顶级窗口
            EnumWindows((hWnd, lParam) =>
            {
                // 1. 检查窗口是否可见
                if (!IsWindowVisible(hWnd))
                    return true; // 跳过不可见的窗口

                // 2. 获取窗口所属的进程 ID
                int processId;
                GetWindowThreadProcessId(hWnd, out processId);

                // 3. 只处理目标进程的窗口
                if (processId != targetProcessId)
                    return true; // 跳过不属于目标进程的窗口

                // 4. 获取窗口标题长度
                int length = GetWindowTextLength(hWnd);
                if (length == 0)
                    return true; // 跳过没有标题的窗口

                // 5. 获取窗口标题
                var sb = new StringBuilder(length + 1);
                GetWindowText(hWnd, sb, sb.Capacity);
                string windowTitle = sb.ToString();

                // 6. 检查窗口标题是否以指定的后缀结尾
                if (windowTitle.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
                {
                    // 将符合条件的窗口添加到结果列表
                    result.Add((hWnd, windowTitle));
                }

                return true; // 继续枚举下一个窗口
            }, IntPtr.Zero);

            return result;
        }

        /// <summary>
        /// 关闭满足条件的窗口
        /// </summary>
        /// <param name="targetClassName"></param>
        /// <param name="targetTitle"></param>
        public static void CloseWindow(IntPtr hWnd)
        {
            try
            {
                // 获取窗口尺寸
                RECT rect = default;
                if (GetWindowRect(hWnd, ref rect))
                {
                    int windowWidth = rect.Right - rect.Left;
                    int windowHeight = rect.Bottom - rect.Top;
                    if (windowWidth > 10 && windowHeight > 10)
                    {
                        if (IsWindow(hWnd))
                        {
                            string title = "未知窗口标题";
                            // 2. 获取窗口标题长度
                            int length = GetWindowTextLength(hWnd);
                            if (length != 0)
                            {
                                // 5. 获取窗口标题
                                var sb = new StringBuilder(length + 1);
                                GetWindowText(hWnd, sb, sb.Capacity);
                                title = sb.ToString();
                            }

                            SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); // 发送关闭指令 CloseWindow
                            LogManager.Info($"[CloseWindow] 关闭成功->窗口标题:{title} PID:{hWnd}");
                        }
                        else
                        {
                            LogManager.Error("[CloseWindow] 无效的窗口句柄 PID:{hWnd}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[CloseWindow] 关闭失败->窗口PID:{hWnd}, 原因;{ex.Message}", ex);
            }
        }


        /// <summary>
        /// 关闭所有满足条件的窗口
        /// </summary>
        /// <param name="targetClassName"></param>
        /// <param name="targetTitle"></param>
        public static void CloseAllWindows(String targetClassName, String targetTitle = null)
        {
            try
            {
                foreach (IntPtr hWnd in FindAllWindows(targetClassName, targetTitle))
                {
                    CloseWindow(hWnd);
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[CloseAllWindows] 关闭失败->窗口标题:{targetTitle}, 原因;{ex.Message}", ex);
            }
        }


        /// <summary>
        /// 关闭所有满足条件的QQ窗口
        /// </summary>
        /// <param name="title"></param>
        /// <param name="className">默认窗口类名:TXGuiFoundation</param>
        public static void CloseAllQQWindows(string title, string className = "TXGuiFoundation")
        {
            try
            {
                foreach (IntPtr hWnd in FindAllWindows(className, title))
                {
                    CloseWindow(hWnd);

                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[CloseAllQQWindows] 关闭失败->窗口标题:{title}, 原因;{ex.Message}", ex);
            }
        }
        public static void CloseAllQQWindowsEndsWith(string title, string className = "TXGuiFoundation")
        {
            CloseAllWindowsEndsWith(className, title);
        }

        /// <summary>
        /// 关闭所有满足条件的QQ窗口
        /// </summary>
        /// <param name="titles"></param>
        /// <param name="className"></param>
        public static void CloseAllQQWindows(string[] titles, string className = "TXGuiFoundation")
        {
            try
            {
                EnumWindows((hWnd, lParam) =>
                {
                    // 检查窗口是否可见
                    if (!IsWindowVisible(hWnd))
                        return true; // 跳过不可见的窗口

                    // 获取窗口类名
                    var classNameBuilder = new StringBuilder(256);
                    GetClassName(hWnd, classNameBuilder, classNameBuilder.Capacity);

                    // 获取窗口标题
                    var windowTitleBuilder = new StringBuilder(256);
                    GetWindowText(hWnd, windowTitleBuilder, windowTitleBuilder.Capacity);

                    // 检查窗口类名和标题是否匹配
                    if (classNameBuilder.ToString().Equals(className, StringComparison.Ordinal))
                    {
                        foreach (var title in titles)
                        {
                            if (windowTitleBuilder.ToString().Equals(title, StringComparison.Ordinal))
                            {
                                CloseWindow(hWnd);
                                break;
                            }
                        }
                    }

                    return true; // 继续遍历所有窗口
                }, IntPtr.Zero);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[CloseAllQQWindows] 关闭失败->窗口标题:{string.Join(", ", titles)}, 原因;{ex.Message}", ex);
            }
        }



        /// <summary>
        /// 关闭所有以特定标题结尾的窗口
        /// </summary>
        /// <param name="targetClassName"></param>
        /// <param name="targetTitle"></param>
        public static void CloseAllWindowsEndsWith(String targetClassName, String targetTitle)
        {
            try
            {

                EnumWindowsProc callback = (hWnd, lParam) =>
                {
                    // 1. 检查窗口是否可见
                    if (!IsWindowVisible(hWnd))
                        return true; // 跳过不可见的窗口
                                     // 2. 获取窗口标题长度
                    int length = GetWindowTextLength(hWnd);
                    if (length == 0)
                        return true; // 跳过没有标题的窗口


                    // 5. 获取窗口标题
                    var sb = new StringBuilder(length + 1);
                    GetWindowText(hWnd, sb, sb.Capacity);
                    string windowTitle = sb.ToString();

                    // 6. 检查窗口标题是否以指定的后缀结尾
                    if (windowTitle.EndsWith(targetTitle))
                    {
                        CloseWindow(hWnd);
                    }
                    return true; // 继续遍历所有窗口
                };
                EnumWindows(callback, IntPtr.Zero);
            }
            catch (Exception ex)
            {
                LogManager.Info($"[CloseAllWindowsEndsWith] 关闭失败->窗口标题: {targetTitle}, 原因:{ex.Message}", ex);
            }
        }

        /// <summary>
        /// 隐藏除指定窗口外的所有窗口
        /// </summary>
        /// <param name="targetTitle"></param>
        /// <param name="className"></param>
        /// <param name="exceptHandle"></param>
        public static void HideAllWindowsExcept(string targetTitle, string className, IntPtr exceptHandle)
        {
            try
            {
                EnumWindows((hWnd, lParam) =>
                {
                    // 跳过指定的窗口
                    if (hWnd == exceptHandle)
                        return true;

                    // 获取窗口类名
                    var classNameBuilder = new StringBuilder(256);
                    GetClassName(hWnd, classNameBuilder, classNameBuilder.Capacity);

                    // 获取窗口标题
                    var windowTitleBuilder = new StringBuilder(256);
                    GetWindowText(hWnd, windowTitleBuilder, windowTitleBuilder.Capacity);

                    // 检查窗口类名和标题是否匹配
                    if (classNameBuilder.ToString().Equals(className, StringComparison.Ordinal) &&
                        windowTitleBuilder.ToString().Equals(targetTitle, StringComparison.Ordinal))
                    {
                        // 隐藏窗口
                        ShowWindow(hWnd, SW_HIDE);
                    }

                    return true; // 继续遍历所有窗口
                }, IntPtr.Zero);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[HideAllWindowsExcept] 隐藏窗口时发生错误: {ex.Message}", ex);
            }
        }


        public static async void MoveWindowsToPosition(IntPtr handle, int targetX, int targetY)
        {
            try
            {
                // 还原窗口
                ShowWindow(handle, SW_RESTORE);
                // 获取窗口矩形
                RECT rect = default;
                if (GetWindowRect(handle, ref rect))
                {
                    int windowWidth = rect.Right - rect.Left;
                    int windowHeight = rect.Bottom - rect.Top;

                    // 计算目标位置
                    int x = targetX == Screen.PrimaryScreen.Bounds.Width ? targetX - windowWidth : targetX;
                    int y = targetY;

                    // 移动窗口到目标位置
                    SetWindowPos(handle, IntPtr.Zero, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
                    await Task.Delay(100);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"移动窗口时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 判断进程是否存在
        /// </summary>
        /// <param name="processName"></param>
        /// <returns></returns>
        public static bool IsProcessRunning(string processName)
        {
            try
            {
                Process[] processes = Process.GetProcessesByName(processName);
                return processes.Length > 0;
            }
            catch (Exception ex)
            {
                LogManager.Error($"[判断进程是否存在] 进程:{processName} 发生异常: {ex.Message}", ex);
                return false;
            }
        }
        /// <summary>
        /// 关闭所有进程
        /// </summary>
        /// <param name="processName"></param>
        public static void CloseAllProcess(string processName)
        {
            // 执行cmd 命令关闭进程
            try
            {
                string command = $"taskkill /f /im {processName}";
                string output = ExecuteCommand(command);
                LogManager.Info($"关闭进程 {processName} 输出: {output}");
            }
            catch (Exception ex)
            {
                LogManager.Error($"关闭进程 {processName} 时发生异常: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 执行DOS命令并返回输出
        /// </summary>
        /// <param name="command">要执行的DOS命令</param>
        /// <returns>命令的输出</returns>
        public static string ExecuteCommand(string command)
        {
            try
            {
                // 创建一个新的 ProcessStartInfo 对象
                ProcessStartInfo processInfo = new ProcessStartInfo
                {
                    FileName = "cmd.exe", // 使用 cmd.exe 执行命令
                    Arguments = $"/c {command}", // /c 参数表示执行命令后关闭 cmd.exe
                    RedirectStandardOutput = true, // 重定向标准输出
                    RedirectStandardError = true, // 重定向标准错误
                    UseShellExecute = false, // 不使用操作系统外壳程序启动进程
                    CreateNoWindow = true // 不创建新窗口
                };

                // 启动进程
                using (Process process = new Process { StartInfo = processInfo })
                {
                    process.Start();

                    // 读取标准输出
                    string output = process.StandardOutput.ReadToEnd();
                    // 读取标准错误
                    string error = process.StandardError.ReadToEnd();

                    // 等待进程退出
                    process.WaitForExit();

                    // 如果有错误，抛出异常
                    if (!string.IsNullOrEmpty(error))
                    {
                        throw new Exception($"命令执行失败: {error}");
                    }

                    return output;
                }
            }
            catch (Exception ex)
            {
                // 记录日志或处理异常
                LogManager.Error($"执行命令时发生异常: {ex.Message}", ex);
                return $"执行命令时发生异常: {ex.Message}";
            }
        }
    }
}
